package com.pond.pond.service.impl;

import com.pond.pond.domain.CommunityPost;
import com.pond.pond.domain.CommunityPostComment;
import com.pond.pond.domain.CommunityPostImage;
import com.pond.pond.mapper.CommunityPostMapper;
import com.pond.pond.service.ICommunityPostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 社区帖子Service业务层处理
 *
 * @author ruoyi
 * @date 2024-03-15
 */
@Service
public class CommunityPostServiceImpl implements ICommunityPostService {
    
    @Autowired
    private CommunityPostMapper communityPostMapper;

    /**
     * 查询社区帖子列表
     *
     * @param communityPost 社区帖子
     * @param userId 当前用户ID（用于判断点赞收藏状态）
     * @return 社区帖子集合
     */
    @Override
    public List<CommunityPost> selectCommunityPostList(CommunityPost communityPost, Long userId) {
        return communityPostMapper.selectCommunityPostList(communityPost, userId);
    }

    /**
     * 查询社区帖子详情
     *
     * @param id 社区帖子主键
     * @param userId 当前用户ID
     * @return 社区帖子
     */
    @Override
    public CommunityPost selectCommunityPostById(Long id, Long userId) {
        return communityPostMapper.selectCommunityPostById(id, userId);
    }

    /**
     * 新增社区帖子
     *
     * @param communityPost 社区帖子
     * @return 结果
     */
    @Override
    public int insertCommunityPost(CommunityPost communityPost) {
        int result = communityPostMapper.insertCommunityPost(communityPost);
        
        // 处理图片数据
        if (result > 0 && communityPost.getImages() != null && !communityPost.getImages().isEmpty()) {
            for (int i = 0; i < communityPost.getImages().size(); i++) {
                CommunityPostImage image = communityPost.getImages().get(i);
                image.setPostId(communityPost.getId());
                image.setSortOrder(i);
                communityPostMapper.insertCommunityPostImage(image);
            }
        }
        
        return result;
    }

    /**
     * 修改社区帖子
     *
     * @param communityPost 社区帖子
     * @return 结果
     */
    @Override
    public int updateCommunityPost(CommunityPost communityPost) {
        int result = communityPostMapper.updateCommunityPost(communityPost);
        
        // 处理图片数据
        if (result > 0 && communityPost.getImages() != null) {
            // 先删除原有图片
            communityPostMapper.deleteCommunityPostImagesByPostId(communityPost.getId());
            
            // 插入新图片
            for (int i = 0; i < communityPost.getImages().size(); i++) {
                CommunityPostImage image = communityPost.getImages().get(i);
                image.setPostId(communityPost.getId());
                image.setSortOrder(i);
                communityPostMapper.insertCommunityPostImage(image);
            }
        }
        
        return result;
    }

    /**
     * 批量删除社区帖子
     *
     * @param ids 需要删除的社区帖子主键集合
     * @return 结果
     */
    @Override
    public int deleteCommunityPostByIds(Long[] ids) {
        return communityPostMapper.deleteCommunityPostByIds(ids);
    }

    /**
     * 删除社区帖子信息
     *
     * @param id 社区帖子主键
     * @return 结果
     */
    @Override
    public int deleteCommunityPostById(Long id) {
        return communityPostMapper.deleteCommunityPostById(id);
    }

    /**
     * 点赞/取消点赞帖子
     *
     * @param postId 帖子ID
     * @param userId 用户ID
     * @return 操作结果
     */
    @Override
    public Map<String, Object> toggleLike(Long postId, Long userId) {
        Map<String, Object> result = new HashMap<>();
        
        // 检查是否已点赞
        boolean isLiked = communityPostMapper.checkUserLiked(postId, userId);
        
        if (isLiked) {
            // 取消点赞
            communityPostMapper.deleteLike(postId, userId);
            communityPostMapper.decrementLikeCount(postId);
            result.put("isLiked", false);
            result.put("action", "unlike");
        } else {
            // 点赞
            communityPostMapper.insertLike(postId, userId);
            communityPostMapper.incrementLikeCount(postId);
            result.put("isLiked", true);
            result.put("action", "like");
        }
        
        // 获取最新点赞数
        int likeCount = communityPostMapper.getLikeCount(postId);
        result.put("likeCount", likeCount);
        
        return result;
    }

    /**
     * 收藏/取消收藏帖子
     *
     * @param postId 帖子ID
     * @param userId 用户ID
     * @return 操作结果
     */
    @Override
    public Map<String, Object> toggleFavorite(Long postId, Long userId) {
        Map<String, Object> result = new HashMap<>();
        
        // 检查是否已收藏
        boolean isFavorited = communityPostMapper.checkUserFavorited(postId, userId);
        
        if (isFavorited) {
            // 取消收藏
            communityPostMapper.deleteFavorite(postId, userId);
            result.put("isFavorited", false);
            result.put("action", "unfavorite");
        } else {
            // 收藏
            communityPostMapper.insertFavorite(postId, userId);
            result.put("isFavorited", true);
            result.put("action", "favorite");
        }
        
        return result;
    }

    /**
     * 增加帖子阅读量
     *
     * @param postId 帖子ID
     * @return 新的阅读量
     */
    @Override
    public int incrementReadCount(Long postId) {
        communityPostMapper.incrementReadCount(postId);
        return communityPostMapper.getReadCount(postId);
    }

    /**
     * 获取帖子评论列表
     *
     * @param postId 帖子ID
     * @param userId 当前用户ID
     * @return 评论列表
     */
    @Override
    public List<CommunityPostComment> selectCommentsByPostId(Long postId, Long userId) {
        return communityPostMapper.selectCommentsByPostId(postId, userId);
    }

    /**
     * 发表评论
     *
     * @param comment 评论信息
     * @return 评论ID
     */
    @Override
    public Long addComment(CommunityPostComment comment) {
        communityPostMapper.insertComment(comment);
        // 增加帖子评论数
        communityPostMapper.incrementCommentCount(comment.getPostId());
        return comment.getId();
    }

    /**
     * 删除评论
     *
     * @param commentId 评论ID
     * @param userId 用户ID
     * @return 是否成功
     */
    @Override
    public boolean deleteComment(Long commentId, Long userId) {
        // 检查评论是否属于该用户
        CommunityPostComment comment = communityPostMapper.selectCommentById(commentId);
        if (comment != null && comment.getUserId().equals(userId)) {
            int result = communityPostMapper.deleteComment(commentId);
            if (result > 0) {
                // 减少帖子评论数
                communityPostMapper.decrementCommentCount(comment.getPostId());
                return true;
            }
        }
        return false;
    }

    /**
     * 点赞/取消点赞评论
     *
     * @param commentId 评论ID
     * @param userId 用户ID
     * @return 操作结果
     */
    @Override
    public Map<String, Object> toggleCommentLike(Long commentId, Long userId) {
        Map<String, Object> result = new HashMap<>();
        
        // 检查是否已点赞
        boolean isLiked = communityPostMapper.checkCommentLiked(commentId, userId);
        
        if (isLiked) {
            // 取消点赞
            communityPostMapper.deleteCommentLike(commentId, userId);
            communityPostMapper.decrementCommentLikeCount(commentId);
            result.put("isLiked", false);
            result.put("action", "unlike");
        } else {
            // 点赞
            communityPostMapper.insertCommentLike(commentId, userId);
            communityPostMapper.incrementCommentLikeCount(commentId);
            result.put("isLiked", true);
            result.put("action", "like");
        }
        
        // 获取最新点赞数
        int likeCount = communityPostMapper.getCommentLikeCount(commentId);
        result.put("likeCount", likeCount);
        
        return result;
    }

    /**
     * 获取热门帖子
     *
     * @param limit 数量限制
     * @param type 排序类型：read-按阅读量，like-按点赞数，comment-按评论数
     * @return 热门帖子列表
     */
    @Override
    public List<CommunityPost> selectHotPosts(Integer limit, String type) {
        return communityPostMapper.selectHotPosts(limit, type);
    }

    /**
     * 获取用户收藏的帖子
     *
     * @param userId 用户ID
     * @return 收藏帖子列表
     */
    @Override
    public List<CommunityPost> selectUserFavorites(Long userId) {
        return communityPostMapper.selectUserFavorites(userId);
    }

    /**
     * 获取用户发布的帖子
     *
     * @param userId 用户ID
     * @return 用户帖子列表
     */
    @Override
    public List<CommunityPost> selectUserPosts(Long userId) {
        return communityPostMapper.selectUserPosts(userId);
    }

    @Override
    public List<Map<String, Object>> selectUserCommentsWithPostTitle(Long userId) {
        return communityPostMapper.selectUserCommentsWithPostTitle(userId);
    }
}